<template>
  <div id="container"></div>
</template>

<script>
export default {
  name: 'SelectLocationInMap',
}
</script>

<script setup>
import { onMounted, onUnmounted, watch } from "vue";
import { getInstance, getAddress } from "@/utils/amap"
const emit = defineEmits(['select'])
const props = defineProps({
  lng: {
    type: Number,
    required: true
  },
  lat: {
    type: Number,
    required: true
  }
})

watch([() => props.lng, () => props.lat], async ([newValue, newValue2], [oldValue , oldValue2]) => {
  if(map){
    map.setCenter([newValue, newValue2])
    map.setZoom(12)
    addMarker(newValue, newValue2)
  }
})


let map = null;
let marker = null;
let position = null;
onMounted(() => {
  getInstance().then((instance) => {
    let tmpLng = 113.324553
    let tmpLat = 23.106414
    if(props.lng && props.lat){
      tmpLng = props.lng
      tmpLat = props.lat
    }
    map = new instance.AMap.Map("container", {
      // 设置地图容器id
      viewMode: "3D", // 是否为3D地图模式
      zoom: 12, // 初始化地图级别
      center: [tmpLng, tmpLat], // 初始化地图中心点位置
    });
    addMarker(tmpLng, tmpLat)
    map.on('click', function(e) {
      addMarker(e.lnglat.getLng(), e.lnglat.getLat())
      getAddress(e.lnglat.getLng(), e.lnglat.getLat()).then((address) => {
        emit('select', { lng : e.lnglat.getLng(), lat : e.lnglat.getLat(), address: address.regeocode.formattedAddress})
      })
    });
  })
});

function addMarker(lng, lat){
  if (marker) {
    map.remove(marker)
  }
  position = new AMap.LngLat(lng, lat)
  marker = new AMap.Marker({
      position: position,
  })
  map.add(marker)
}

onUnmounted(() => {
  map?.destroy();
});
</script>

<style scoped>
#container {
  width: 100%;
  height: 100%;
}
</style>
